<template>
	<l-page :page.sync="queryParams.pageNum" :page-size.sync="queryParams.pageSize" :total="total" @getList="getList">
		<el-form ref="queryForm" slot="header" :inline="true" :model="queryParams" label-width="90px">
			<el-form-item label="活动编号:" prop="activeSn">
				<el-input v-model.trim="queryParams.activeSn" clearable placeholder="请输入活动编号" show-word-limit />
			</el-form-item>
			<el-form-item label="商品ID:" prop="goodsId">
				<el-input v-model.trim="queryParams.goodsId" clearable placeholder="请输入商品ID" maxlength="11" show-word-limit />
			</el-form-item>
			<el-form-item label="商品名称:" prop="goodsName">
				<el-input v-model.trim="queryParams.goodsName" clearable placeholder="请输入商品名称" />
			</el-form-item>
			<el-form-item label="供应商名称:" prop="supplierName">
				<el-input v-model.trim="queryParams.supplierName" clearable placeholder="请输入供应商名称" />
			</el-form-item>
			<el-form-item label="专区名称:" prop="zoneId">
				<el-select v-model.trim="queryParams.zoneId" class="el-input-240" clearable filterable placeholder="请选择专区名称">
					<el-option v-for="(value, index) in zoneList" :key="index" :label="value.zoneName" :value="value.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="商品状态:" prop="status">
				<el-select v-model="queryParams.status" clearable filterable placeholder="请选择商品状态">
					<el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
				</el-select>
			</el-form-item>
			<start-end-time ref="child" :get-time="getTime" title="活动时间:"></start-end-time>
		</el-form>
		<div slot="card" class="mb-[24px] flex items-center">
			<l-statistical-card left-name="拼团成功总金额" :left-value="collage.collageSuccess" :right-value="collage.todayCollageSuccess" />
			<l-statistical-card left-name="拼团失败总金额" :left-value="collage.collageFail" :right-value="collage.todayCollageFail" />
		</div>
		<template slot="options">
			<l-search @search="queryList" @refresh="resetQuery" />
			<el-button icon="el-icon-plus" type="primary" @click="$router.push('collageCreate')">新增</el-button>
			<el-button type="primary" @click="$router.push('blockRecord')">
				<svg-icon icon-class="grouping" size="16px"></svg-icon>
				拼团记录</el-button
			>
			<el-button type="primary" class="!w-[120px]" @click="handleShowIntegralOpen">
				<svg-icon icon-class="integral" size="16px"></svg-icon>
				商城首页开关</el-button
			>
		</template>
		<el-table v-loading="loading" :data="goodsList" stripe>
			<el-table-column :formatter="emptyToString" align="center" label="序号" type="index" width="50"> </el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="活动编号" prop="activeSn" min-width="156"></el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="专区名称" prop="zoneName" min-width="120"></el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品ID" prop="goodsId" min-width="120"></el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品名称" prop="goodsName" show-overflow-tooltip width="150px">
				<template slot-scope="scope">
					<div class="goods-name-style">
						{{ scope.row.goodName }}
					</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品图片">
				<template slot-scope="scope">
					<el-image :preview-src-list="[scope.row.picUrl]" :src="scope.row.picUrl" style="width: 50px; height: 50px"></el-image>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="供应商名称" prop="supplierName" min-width="120"></el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品价格（元）" prop="price" min-width="156"> </el-table-column>
			<el-table-column :formatter="emptyToNumber" align="center" label="拼团价格（元）" prop="collagePrice" min-width="156" />
			<el-table-column :formatter="emptyToNumber" align="center" label="拼团人数" prop="collageCount" min-width="120" />
			<el-table-column :formatter="emptyToNumber" align="center" label="拼团时长（h）" prop="collageTime" min-width="156" />
			<el-table-column :formatter="emptyToNumber" align="center" label="销量" prop="numberGet" min-width="120"></el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品状态" prop="status" min-width="156">
				<template slot-scope="scope">
					<el-switch
						v-model="scope.row.status"
						:active-value="1"
						:inactive-value="0"
						active-text="开启"
						class="switch"
						inactive-text="禁用"
						@change="statusChange($event, scope.row.collageId)"
					></el-switch>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToNumber" align="center" label="是否参与分佣" prop="isBonus" min-width="120">
				<template slot-scope="scope">
					<el-switch
						v-model="scope.row.isBonus"
						:active-value="1"
						:inactive-value="0"
						active-text="开启"
						class="switch"
						inactive-text="禁用"
						@change="bonusChange($event, scope.row.collageId)"
					></el-switch>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="展示顺序" min-width="156" prop="sortOrder">
				<template slot-scope="scope">
					<el-button :circle="true" class="sortOrder" icon="el-icon-caret-top" size="mini" type="primary" @click="reSortOrderReduce(scope.row)"></el-button>
					<el-button :circle="true" class="sortOrder" icon="el-icon-caret-bottom" size="mini" type="primary" @click="reSortOrderPlus(scope.row)"></el-button>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="活动时间" min-width="200" prop="createTime">
				<template slot-scope="scope">
					<div class="w-full flex flex-col items-center">
						<span>{{ dayjs(scope.row.startTime).format('YYYY-MM-DD HH:mm:ss') }}-</span>
						<span>{{ dayjs(scope.row.endTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column :width="100" align="center" fixed="right" header-align="center" label="操作">
				<template slot-scope="scope">
					<div class="table-action flex justify-center">
						<el-button type="danger" @click="handleDel(scope.row.collageId)">删除</el-button>
					</div>
				</template>
			</el-table-column>
		</el-table>
		<l-dialog
			v-model="showIntegralOpen"
			title="商城首页显示配置"
			width="477px"
			:show-ok-button="false"
			@formClose="showIntegralOpen = false"
			@close="showIntegralOpen = false"
			@formSubmit="showIntegralOpen = false"
		>
			<el-form :inline="true" label-width="150px">
				<el-form-item label="是否显示在商城首页:">
					<el-switch v-model="dictData.dictValue" active-value="1" inactive-value="0" active-text="开启" class="switch" inactive-text="关闭" @change="handleUpdateStatus(dictData)"></el-switch>
				</el-form-item>
			</el-form>
		</l-dialog>
	</l-page>
</template>
<script>
import { getZoneGoodsList, getZoneList } from '@/api/mall/prefecture';
import { addCollage, delCollage, getCollage, listCollage, updateCollage } from '@/api/mall/collage';
import startEndTime from '@/components/StartEndTime';
import debounce from 'lodash/debounce';
import tableMixins from '@/mixins/table';

export default {
	name: 'Collage',
	components: { startEndTime },
	mixins: [tableMixins],
	data() {
		return {
			choiceDate0: '',
			pickerOptions: {
				// 设置不能选择的日期
				onPick: ({ maxDate, minDate }) => {
					if (minDate) {
						//如果默认有最小日期
						this.choiceDate0 = minDate.getTime();
					} else {
						//如果最小日期被清空，则最小日期为当天
						this.choiceDate0 = new Date();
					}
					if (maxDate) {
						this.choiceDate0 = '';
					}
				},
				disabledDate: (time) => {
					let choiceDateTime = new Date(this.choiceDate0).getTime(); //选中的第一个日期
					if (this.choiceDate0) {
						//14天的时间戳:15*24*3600*1000=1296000000
						return time.getTime() > choiceDateTime + 1296000000 || time.getTime() < choiceDateTime - 1296000000;
					}
				},
			},
			collageTime: '',
			collagePrice: '',
			collageCount: '',
			editForm: {},
			title1: '',
			showFlag: false,
			price: '',
			date: '',
			zoneId: '',
			selectShowFlag: false,
			loading: true,
			// 是否显示弹出层
			open: false,
			// 搜索参数
			queryParams: {
				pageNum: 1,
				activeSn: null,
				goodsId: null,
				pageSize: 10,
				zoneId: null,
				status: null,
				supplierName: null,
				name: null,
				date: [],
				goodsName: null,
			},
			goodsList: [],
			statusList: [
				{
					value: null,
					label: '全部',
				},
				{
					value: 0,
					label: '下架',
				},
				{
					value: 1,
					label: '上架',
				},
			],
			// 表单参数
			form: {},
			total: 0,
			showAdd: false,
			// 表单校验
			rules: {
				sort: [
					{ required: true, message: '排序不能为空' },
					{ type: 'number', message: '排序必须为数字值' },
				],
				collageTime: [
					{ required: true, message: '拼团时长不能为空' },
					{ type: 'number', message: '拼团时长必须为数字值' },
				],
				collageCount: [
					{ required: true, message: '拼团人数不能为空' },
					{ type: 'number', message: '拼团人数必须为数字值' },
				],
				collagePrice: [
					{ required: true, message: '拼团金额不能为空' },
					{ type: 'number', message: '拼团金额必须为数字值' },
				],
			},
			goodsDetail: '',
			detailDialogVisible: false,
			zoneList: [],
			goodsForm: {
				pageNum: 1,
				pageSize: 10,
				name: null,
			},
			selectList: [],
			addGoodsFlag: false,
			goodsTotal: 0,
			zoneName: '',
			goodsZoneList: [],
			selectListNow: [],
			disable: true,
			collageId: '',
			collage: {
				collageFail: 0,
				collageSuccess: 0,
				todayCollageFail: 0,
				todayCollageSuccess: 0,
			},
			dictData: {},
			showIntegralOpen: false,
		};
	},

	created() {
		this.getList();
		this.getZoneList();
		this.getCollageCount();
	},
	methods: {
		handleShowIntegralOpen() {
			this.$request.get('/system/dict/data/list?pageNum=1&pageSize=10&dictType=index_config').then((res) => {
				let data = res.rows;
				for (let i = 0; i < data.length; i++) {
					if (data[i].dictLabel === 'pt_show') {
						this.dictData = data[i];
						this.showIntegralOpen = true;
						return;
					}
				}
			});
		},
		handleUpdateStatus(data) {
			this.$request.put('/system/dict/data', data).then(() => {
				this.$message.success('编辑成功');
			});
		},
		getCollageCount() {
			this.$request.get('/system/collage/collageCount').then((res) => {
				this.collage = res.data;
			});
		},
		statusChange(event, row) {
			this.loading = true;
			this.$request
				.post('/system/collage/edit', {
					id: row,
					status: event,
				})
				.then(() => {
					this.msgSuccess('编辑成功');
					this.getList();
				});
		},
		bonusChange(event, row) {
			this.$request
				.post('/system/collage/edit', {
					id: row,
					isBonus: event,
				})
				.then(() => {
					this.msgSuccess('编辑成功');
					this.getList();
				});
		},
		reSortOrderReduce(row) {
			this.$request
				.post('/system/collage/reSortOrderReduce', {
					id: row.collageId,
				})
				.then(() => {
					this.getList();
				});
		},
		reSortOrderPlus(row) {
			this.$request
				.post('/system/collage/reSortOrderPlus', {
					id: row.collageId,
				})
				.then(() => {
					this.getList();
				});
		},
		goHistory() {
			this.$router.push({
				path: '/marketing/cutHistory',
			});
		},
		handleClose3() {
			this.showFlag = false;
			this.editForm = {};
			this.$refs['editForm'].resetFields();
		},
		batchEditCount() {
			console.log(this.date);
			for (let i = 0; i < this.selectListNow.length; i++) {
				this.$set(this.selectListNow[i], 'collageCount', this.collageCount);
			}
		},
		batchEditTime() {
			console.log(this.date);
			for (let i = 0; i < this.selectListNow.length; i++) {
				this.$set(this.selectListNow[i], 'collageTime', this.collageTime);
			}
		},
		batchEditPrice() {
			for (let i = 0; i < this.selectListNow.length; i++) {
				this.$set(this.selectListNow[i], 'collagePrice', this.collagePrice);
			}
		},
		goodsCommit: debounce(
			function () {
				console.log(this.selectListNow);
				for (let i = 0; i < this.selectListNow.length; i++) {
					if (!this.selectListNow[i].collagePrice) {
						this.$message.error('请输入商品的拼团金额');
						return;
					}
					if (!this.selectListNow[i].collageCount) {
						this.$message.error('请输入商品的拼团人数');
						return;
					}
					if (!this.selectListNow[i].sort) {
						this.$message.error('请添加商品的排序');
						return;
					}

					delete this.selectListNow[i].tenantId;
					this.selectListNow[i].zoneId = this.zoneId;
					this.selectListNow[i].originPrice = this.selectListNow[i].price;
					let a = this.selectListNow[i].startTime;
					this.selectListNow[i].endTime = this.selectListNow[i].startTime[1];
					this.selectListNow[i].startTime = this.selectListNow[i].startTime[0];
				}
				addCollage(this.selectListNow).then((res) => {
					this.$message.success('新增商品成功!');
					this.showAdd = false;
					this.handleClose();
					this.getList();
				});
			},
			1500,
			{
				leading: true,
				trailing: false,
			}
		),
		queryGoodsList() {
			this.goodsForm.pageNum = 1;
			this.getGoodsList();
		},
		getGoodsList() {
			this.goodsForm.zoneId = this.zoneId;
			getZoneGoodsList(this.goodsForm).then((response) => {
				this.goodsZoneList = response.data.records;
				this.goodsTotal = response.data.total;
				this.addGoodsFlag = true;
			});
		},
		submit() {
			this.selectListNow = this.selectList;
			this.addGoodsFlag = false;
		},
		selectGoodsChange(value) {
			this.selectList = value;
		},
		handleClose2() {
			this.goodsForm = {
				pageNum: 1,
				pageSize: 10,
				name: null,
			};
			this.selectList = [];
			this.addGoodsFlag = false;
		},
		getZoneList() {
			getZoneList({}).then((res) => {
				this.zoneList = res.data;
			});
		},
		selectShow() {
			this.addGoodsFlag = true;
			this.getGoodsList();
		},
		handleClose() {
			this.showAdd = false;
			this.price = '';
			this.selectListNow = [];
			if (this.$refs.selectTable) {
				this.$refs.selectTable.clearSelection();
			}

			this.selectList = [];
			this.zoneId = '';
		},
		resetQuery() {
			this.$refs.child.resetTime(); //清空时间
			this.$refs.queryForm.resetFields();
			this.queryList();
		},
		//获取时间
		getTime(startTime, endTime) {
			this.$set(this.queryParams.date, 0, startTime);
			this.$set(this.queryParams.date, 1, endTime);
		},

		queryList() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		getList() {
			this.loading = true;
			if (this.queryParams.date) {
				this.queryParams.startTime = this.queryParams.date[0];
				this.queryParams.endTime = this.queryParams.date[1];
			}
			listCollage(this.queryParams)
				.then((response) => {
					this.goodsList = response.data.records;
					this.total = response.data.total;
					this.setActionWidth();
				})
				.finally(() => {
					this.loading = false;
				});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {};
			this.resetForm('form');
		},
		getCollageGoodsDetails(id) {
			getCollage({ id }).then((res) => {
				this.editForm = res.data;
				this.editForm.startTime = [res.data.startTime, res.data.endTime];
			});
		},
		handleUpdate(id) {
			this.getCollageGoodsDetails(id);
			this.showFlag = true;
			this.disable = true;
			this.title1 = '详情';
		},
		submitEdit() {
			this.$refs['editForm'].validate((valid) => {
				if (valid) {
					let obj = {
						id: this.collageId,
						collagePrice: this.editForm.collagePrice,
						collageCount: this.editForm.collageCount,
						collageTime: this.editForm.collageTime,
						sort: this.editForm.sort,
						startTime: this.editForm.startTime[0],
						endTime: this.editForm.startTime[1],
					};
					updateCollage(obj).then((res) => {
						this.$message.success('编辑商品成功!');
						this.getList();
						this.handleClose3();
					});
				}
			});
		},
		handleEdit(id) {
			this.collageId = id;
			this.getCollageGoodsDetails(id);
			this.showFlag = true;
			this.disable = false;
			this.title1 = '编辑';
		},
		handleDel(id) {
			this.$confirm('是否删除该商品?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					delCollage({
						id: [id],
					}).then(() => {
						this.$message.success('删除商品成功!');
						this.getList();
					});
				})
				.catch((e) => {
					console.log(e);
					this.$message({
						type: 'info',
						message: '已取消删除',
					});
				});
		},
		submitForm() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
				}
			});
		},
		handleAdd() {
			this.showAdd = true;
		},
		handleCommand(key, row) {
			this[key](row);
		},
	},
};
</script>
<style lang="scss" scoped>
.sortOrder {
	background: #ffffff;
	border-color: #cccccc;
	color: #86909c;
}

.sortOrder .el-icon-caret-top {
	color: #cccccc;
}

.sortOrder .el-icon-caret-bottom {
	color: #cccccc;
}

.btn-box {
	display: flex;
	justify-content: center;

	.btn2 {
		background: #1a2483;
		opacity: 1;
		border: none;
	}

	.btn {
		width: 236px !important;
		line-height: 60px;
		height: 60px;
		padding: 0;
		text-align: center;
	}
}

.edit-form {
	.goods-info {
		display: flex;
		border-radius: 8px;
		border: 1px dashed transparent;
		background: linear-gradient(white, white) padding-box, repeating-linear-gradient(-45deg, #ccc 0, #ccc 0.25em, white 0, white 0.75em);
		width: 100%;
		height: 127px;
		box-sizing: border-box;
		padding: 14px 18px;

		.right {
			padding-left: 30px;
			font-size: 14px;
			overflow: hidden;
			flex: 1;

			.goods-name {
				color: #333333;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
			}

			.goods-id {
				color: #808a97;
				margin-top: 8px;
			}

			.goods-price {
				color: #f14a46;
				font-weight: 900;
				margin-top: 23px;

				span {
					font-size: 10px;
				}
			}
		}

		img {
			display: block;
			width: 100px;
			height: 100px;
			border-radius: 8px;
		}
	}

	.title {
		text-align: left;
		vertical-align: middle;
		font-size: 14px;
		color: #606266;
		line-height: 40px;
		font-weight: bold;
	}
}

.bottom-btn-box {
	position: relative;
	display: flex;
	justify-content: center;
	margin-top: 20px;

	> div {
		position: absolute;
		font-size: 14px;
		height: 60px;
		line-height: 60px;
		left: 80px;

		span {
			color: #f14a46;
		}
	}

	.btn {
		width: 236px;
		height: 60px;
		padding: 0;
		font-size: 18px;
	}

	.btn2 {
		background: #1a2483;
		border: none;
	}
}

.commit-btn {
	width: 494px;
	height: 60px;
	background: #1a2483;
	opacity: 1;
	padding: 0;
	border-radius: 4px;
	text-align: center;
	margin: 0px auto;
	border: 1px;
	color: #ffffff;
	font-size: 18px;
}

.pl-edit-btn {
	width: 75px;
	height: 35px;
	background: var(--primary-color);
	opacity: 1;
	font-size: 12px;
	padding: 10px 12px;
	text-align: center;
	border: none;
	margin-left: 10px;

	&:hover {
		background: var(--primary-color);
		opacity: 1;
	}
}

.select-btn {
	width: 100px;
	height: 36px;
	background: var(--primary-color);
	opacity: 1;
	border: none;

	&:hover {
		background: var(--primary-color);
		opacity: 1;
	}
}

.search-btn {
	width: 100px;
	height: 36px;
	background: var(--primary-color);
	opacity: 1;
	padding: 0;
	color: #fff;
	border: none;
	border-radius: 4px;
	text-align: center;
	line-height: 36px;
	font-size: 12px;
	display: inline-block;
	cursor: pointer;
	margin-right: 20px;
}

.add-btn {
	width: 100px;
	height: 36px;
	background: #1a2483;
	opacity: 1;
	padding: 0;
	color: #fff;
	border: none;
	border-radius: 4px;
	text-align: center;
	line-height: 36px;
	font-size: 12px;
	cursor: pointer;
}

.table {
	margin-top: 20px;
	border: 1px solid #f7f7f7;
	opacity: 1;
	border-radius: 10px;

	.btn {
		height: 36px;
		border: none;
		border-radius: 4px;
		color: #ffffff;
	}

	.btn1 {
		background: #6373ee;
	}

	.btn2 {
		background: #1d2eb8;
	}

	.btn3 {
		background: #1a2483;
	}
}
</style>
